<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vue指令练习</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.11/vue.min.js"></script>
    <style>
        .image {
            width: 300px;
            height: 140px;
            background-size: cover;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="image" v-for="image in images"  v-lazy="image"></div>
    </div>
    <script>
        Vue.directive('lazy', {
            bind: function (el, binding, vnode) {
                let img = document.createElement("img");
                el.style.backgroundImage = `url('https://epherema.oss-cn-hongkong.aliyuncs.com/images/entry_image_default.png')`;
                img.src = binding.value;
                console.log(binding.value);
                img.onload = function() {
                    el.style.backgroundImage = `url(${binding.value})`;
                }
                img.onerror = function() {
                    el.style.backgroundImage = `url('https://epherema.oss-cn-hongkong.aliyuncs.com/images/entry_image_default.png')`;
                }                
            }
        });
        new Vue({
            el: '#app',
            data: {
                images: [
                    "https://images.unsplash.com/photo-1558252100-d4fb123a1af7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
                    "https://images.unsplash.com/photo-1557998960-05ed9aa698b8?ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
                    "https://images.unsplash.com/photo-1559277118-5967ee694257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
                    "https://images.unsplash.com/photo-1559199496-490b6e15a0b1?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
                    "https://images.unsplash.com/photo-1493175562479-13f62f4fd9de?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
                    "https://images.unsplash.com/photo-1553010037-c6a878840053?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"
                ]
            }
        })
    </script>
</body>
</html>